package com.example.ordersystem.controller;

import com.example.ordersystem.entity.User;
import com.example.ordersystem.entity.vo.ResultMessage;
import com.example.ordersystem.service.UserService;
import com.example.ordersystem.util.EmailUtil;
import com.example.ordersystem.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制类
 */
@RestController
@RequestMapping("order/user")
@CrossOrigin
public class UserController {

    @Autowired
    ResultUtil resultUtil;

    @Autowired
    UserService userService;

    /**
     * 修改密码
     */
    @PostMapping("changePwd")
    public ResultMessage changePwd(@RequestBody User user)
    {
        userService.changePwd(user);
        return resultUtil.success("修改成功");
    }

    /**
     * 用户登录并返回用户id
     */
    @PostMapping("login")
    public ResultMessage login(@RequestBody User user1)
    {
        User user=userService.login(user1);
        if(user!=null)
        {
            return resultUtil.data(user);
        }
        return resultUtil.error("邮箱或密码错误");
    }

    /**
     * 用户注册
     */
    @PostMapping("register")
    public ResultMessage register(@RequestBody User user)
    {
        userService.register(user);
        return resultUtil.success("注册成功");
    }


    /**
     * 发送验证码
     */
    @PostMapping("sendCode")
    public ResultMessage sendCode(@RequestBody HashMap<String,String>map)
    {
        String code= EmailUtil.creatCode(6);
        EmailUtil.sendEmail(code,map.get("mailbox"));
        return resultUtil.data(code);
    }

    /**
     * 根据id获取用户个人信息
     */
    @GetMapping("getInfo/{id}")
    public ResultMessage getInfoById(@PathVariable String id)
    {
           return resultUtil.data(userService.getInfoById(id));
    }

    /**
     * 修改用户个人信息
     */
    @PostMapping("changeInfo")
    public ResultMessage changeInfo(@RequestBody User user)
    {
        userService.changeInfo(user);
        return resultUtil.success("修改成功！");
    }

    /**
     * 修改头像
     */
    @PostMapping("changeAvatar")
    public ResultMessage changeAvatar(@RequestBody Map<String,String> map)
    {
        userService.changeAvatar(map.get("id"),map.get("avatar"));
        return resultUtil.success("修改成功");
    }
    /**
     * 管理员查看用户列表
     */
    @GetMapping("selectUserList/{currentPage}")
    public ResultMessage selectUserList(@PathVariable String currentPage)
    {
        return resultUtil.data(userService.selectUserList(currentPage));
    }

}
